﻿using Lidgren.Network;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;

public class NetChannel : NetPeer
{
    List<NetPlayer> netPlayers = new List<NetPlayer>();
    public NetChannel(NetPeerConfiguration config) : base(config)
    {
        config.AcceptIncomingConnections = true;
        config.AutoFlushSendQueue = true;
    }
    public ActorData GetActor(IPEndPoint SenderEndPoint)
    {
        //var conn  = this.GetConnection(SenderEndPoint);

        var res = netPlayers.Find(x => x.conn.RemoteEndPoint == SenderEndPoint);
        if (res != null)
            return res.actorInfo;
        return null;
    }

    public void ConnectAllPlayer()
    {

    }
    public void SendMsgToPlayer(string playerGUID, NetOutgoingMessage msg, NetDeliveryMethod method)
    {
        var netplayer = netPlayers.Find(x => x.actorInfo.actorGUID == playerGUID);
        if(netplayer != null)
        {
            this.SendMessage(msg, netplayer.conn, method);
        }
   
    }

    /// <summary>
    /// 登录连接记录
    /// </summary>
    /// <param name="acotr"></param>
    /// <param name="conn"></param>
    public void AddLoginConnect(ActorData actor,NetConnection conn)
    {
        NetPlayer player = new NetPlayer();
        player.actorInfo = actor;
        player.conn = conn;
        netPlayers.Add(player);
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    /// <param name="conn"></param>
    public void RemoveConnection(NetConnection conn)
    {
        var netPlayer =  netPlayers.Find(x => x.conn.RemoteUniqueIdentifier == conn.RemoteUniqueIdentifier);
        if(netPlayer != null)
        {
            Log.Info("Remove Connection " + netPlayer.actorInfo.name);
            netPlayers.Remove(netPlayer);
        }
    }
    public void SendToAll(NetOutgoingMessage msg,NetDeliveryMethod method = NetDeliveryMethod.ReliableOrdered)
    {
        if (this.Connections.Count <= 0)
            return;
        foreach (var client in this.Connections)
        {
            this.SendMessage(msg, client, method);
        }
        //FlushSendQueue();
    }

    
}

public class NetPlayer
{
    public NetConnection conn;
    public ActorData actorInfo;


}